package com.netsdk.demo.customize;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.callback.impl.DefaultDisconnectCallback;
import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack;
import com.netsdk.lib.structure.*;
import java.io.File;
import java.text.SimpleDateFormat;
import static com.netsdk.lib.Utils.getOsPrefix;

/**
 * @author 291189
 * @version 1.0
 * @description ERR230208051
 * @date 2023/2/10 13:56
 */
public class AccesscontrolCapsDemo {

    // SDk对象初始化
    public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
    public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE;

    // 判断是否初始化
    private static boolean bInit = false;
    // 判断log是否打开
    private static boolean bLogOpen = false;
    // 设备信息
    private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex();
    // 登录句柄
    private NetSDKLib.LLong m_hLoginHandle = new NetSDKLib.LLong(0);

    // 智能事件订阅句柄
    private NetSDKLib.LLong m_attachHandle = new NetSDKLib.LLong(0);

    // 回调函数需要是静态的，防止被系统回收
    // 断线回调
    private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE();
    // 重连回调
    private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE();

    // 编码格式
    public static String encode;

    static {
        String osPrefix = getOsPrefix();
        if (osPrefix.toLowerCase().startsWith("win32-amd64")) {
            encode = "GBK";
        } else if (osPrefix.toLowerCase().startsWith("linux-amd64")) {
            encode = "UTF-8";
        }
    }

    /**
     * 获取当前时间
     */
    public static String GetDate() {
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDate.format(new java.util.Date()).replaceAll("[^0-9]", "-");
    }

    /**
     * 初始化SDK库
     */
    public static boolean Init() {
        bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时，初始化一次
        if (!bInit) {
            System.out.println("Initialize SDK failed");
            return false;
        }
        // 配置日志
        AccesscontrolCapsDemo.enableLog();

        // 设置断线重连回调接口, 此操作为可选操作，但建议用户进行设置
        netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null);

        // 设置登录超时时间和尝试次数，可选
        // 登录请求响应超时时间设置为3S
        int waitTime = 3000;
        // 登录时尝试建立链接 1 次
        int tryTimes = 1;
        netsdk.CLIENT_SetConnectTime(waitTime, tryTimes);
        // 设置更多网络参数， NET_PARAM 的nWaittime ， nConnectTryNum 成员与 CLIENT_SetConnectTime
        // 接口设置的登录设备超时时间和尝试次数意义相同,可选
        NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM();
        // 登录时尝试建立链接的超时时间
        netParam.nConnectTime = 10000;
        // 设置子连接的超时时间
        netParam.nGetConnInfoTime = 3000;
        netsdk.CLIENT_SetNetworkParam(netParam);
        return true;
    }

    /**
     * 打开 sdk log
     */
    private static void enableLog() {
        NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO();
        File path = new File("sdklog/");
        if (!path.exists())
            path.mkdir();

        // 这里的log保存地址依据实际情况自己调整
        String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + GetDate() + ".log";
        setLog.nPrintStrategy = 0;
        setLog.bSetFilePath = 1;
        System.arraycopy(logPath.getBytes(), 0, setLog.szLogFilePath, 0, logPath.getBytes().length);
        System.out.println(logPath);
        setLog.bSetPrintStrategy = 1;
        bLogOpen = netsdk.CLIENT_LogOpen(setLog);
        if (!bLogOpen)
            System.err.println("Failed to open NetSDK log");
    }

    /**
     * 高安全登录
     */
    public void loginWithHighLevel() {
        // 输入结构体参数
        NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() {
            {
                szIP = m_strIpAddr.getBytes();
                nPort = m_nPort;
                szUserName = m_strUser.getBytes();
                szPassword = m_strPassword.getBytes();
            }
        };
        // 输出结构体参数
        NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();

        // 写入sdk
        m_hLoginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam);
        if (m_hLoginHandle.longValue() == 0) {
            System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort,
                    netsdk.CLIENT_GetLastError());
        } else {
            deviceInfo = pstOutParam.stuDeviceInfo; // 获取设备信息
            System.out.println("Login Success");
            System.out.println("Device Address：" + m_strIpAddr);
            System.out.println("设备包含：" + deviceInfo.byChanNum + "个通道");
        }
    }

    /**
     * 退出
     */
    public void logOut() {
        if (m_hLoginHandle.longValue() != 0) {
            netsdk.CLIENT_Logout(m_hLoginHandle);
            System.out.println("LogOut Success");
        }
    }

    /**
     * 清理sdk环境并退出
     */
    public static void cleanAndExit() {
        if (bLogOpen) {
            netsdk.CLIENT_LogClose(); // 关闭sdk日志打印
        }
        netsdk.CLIENT_Cleanup(); // 进程关闭时，调用一次
        System.exit(0);
    }


    /**
     * 选择通道
     */
    private int channelId = 0;// 逻辑通道

    public void  accesscontrolCaps(){


    //    获取门禁能力, pInBuf = NET_IN_AC_CAPS*, pOutBuf = NET_OUT_AC_CAPS*
        int nType = NetSDKLib.NET_ACCESSCONTROL_CAPS;

        // 入参
        NET_IN_AC_CAPS stIn = new NET_IN_AC_CAPS();


        // 出参
        NET_OUT_AC_CAPS stOut = new NET_OUT_AC_CAPS();

        stIn.write();
        stOut.write();

        boolean bRet = netsdk.CLIENT_GetDevCaps(m_hLoginHandle, nType, stIn.getPointer(), stOut.getPointer(), 3000);
        if(bRet) {
            stOut.read();
            /**
             ACCaps能力集
             */
            NET_AC_CAPS stuACCaps
                    = stOut.stuACCaps;
            System.out.println("ACCaps能力集");

            System.out.println("nChannels:"+stuACCaps.nChannels);
            /**
             是否支持门禁报警日志记录在记录集中
             */
            int bSupAccessControlAlarmRecord
                    = stuACCaps.bSupAccessControlAlarmRecord;
            System.out.println("bSupAccessControlAlarmRecord:"+bSupAccessControlAlarmRecord);

            /**
             AccessControlCustomPassword记录集中密码的保存方式,0:明文,默认值0, 1:MD5
             */
            int nCustomPasswordEncryption
                    = stuACCaps.nCustomPasswordEncryption;
            System.out.println("nCustomPasswordEncryption:"+nCustomPasswordEncryption);
            /**
             是否支持信息功能,0:未知，默认,1:不支持, 2:支持
             */
            int nSupportFingerPrint
                    = stuACCaps.nSupportFingerPrint;
            System.out.println("nSupportFingerPrint:"+nSupportFingerPrint);

            /**
             user操作能力集
             */
            System.out.println("user操作能力集");

            NET_ACCESS_USER_CAPS stuUserCaps=  stOut.stuUserCaps;
            /**
             每次下发的最大数量
             */
            int nMaxInsertRate = stuUserCaps.nMaxInsertRate;
            System.out.println("nMaxInsertRate:"+nMaxInsertRate);

            /**
             用户数量上限
             */
            int nMaxUsers
                    = stuUserCaps.nMaxUsers;
            System.out.println("nMaxUsers:"+nMaxUsers);
            /**
             每个用户可以记录的最大信息数量
             */
            int nMaxFingerPrintsPerUser
                    = stuUserCaps.nMaxFingerPrintsPerUser;
            System.out.println("nMaxFingerPrintsPerUser:"+nMaxFingerPrintsPerUser);
            /**
             每个用户可以记录的最大卡片数量
             */
            int nMaxCardsPerUser
                    = stuUserCaps.nMaxCardsPerUser;
            System.out.println("nMaxCardsPerUser:"+nMaxCardsPerUser);

            /**
             card操作能力集
             */
            NET_ACCESS_CARD_CAPS stuCardCaps
                    = stOut.stuCardCaps;
            System.out.println("card操作能力集");

            /**
             每次下发的最大数量
             */
            int nMaxInsertRate1
                    = stuCardCaps.nMaxInsertRate;
            System.out.println("nMaxInsertRate1:"+nMaxInsertRate1);

            /**
             卡片数量上限
             */
            int nMaxCards
                    = stuCardCaps.nMaxCards;
            System.out.println("nMaxCards:"+nMaxCards);


            /**
             信息操作能力集
             */
            NET_ACCESS_FINGERPRINT_CAPS stuFingerprintCaps
                    = stOut.stuFingerprintCaps;

            System.out.println("信息操作能力集");

            /**
             每次下发的最大数量
             */
            int nMaxInsertRate2
                    = stuFingerprintCaps.nMaxInsertRate;
            System.out.println("nMaxInsertRate2:"+nMaxInsertRate2);

            /**
             单信息数据的最大字节数
             */
            int nMaxFingerprintSize = stuFingerprintCaps.nMaxFingerprintSize;
            System.out.println("nMaxFingerprintSize:"+nMaxFingerprintSize);

            /**
             信息数量上限
             */
            int nMaxFingerprint = stuFingerprintCaps.nMaxFingerprint;

            System.out.println("nMaxFingerprint:"+nMaxFingerprint);


            /**
             目标操作能力集
             */
            NET_ACCESS_FACE_CAPS stuFaceCaps
                    = stOut.stuFaceCaps;

            System.out.println("目标操作能力集");
            /**
             每次下发的最大数量
             */
            int nMaxInsertRate3
                    = stuFaceCaps.nMaxInsertRate;
            System.out.println("nMaxInsertRate3:"+nMaxInsertRate3);

            /**
             目标存储上限
             */
            int nMaxFace
                    = stuFaceCaps.nMaxFace;
            System.out.println("nMaxFace:"+nMaxFace);

            /**
             目标识别类型，0:白光 1:红外
             */
            int nRecognitionType
                    = stuFaceCaps.nRecognitionType;
            System.out.println("nRecognitionType:"+nRecognitionType);
            /**
             目标识别算法，0:未知1:华2:商3:依4:汉5:火
             */
            int nRecognitionAlgorithm
                    = stuFaceCaps.nRecognitionAlgorithm;
            System.out.println("nRecognitionAlgorithm:"+nRecognitionAlgorithm);

            /**
             眼睛相关能力集
             */
            NET_ACCESS_IRIS_CAPS stuIrisCaps
                    = stOut.stuIrisCaps;

            System.out.println("眼睛相关能力集");

            /**
             每次最大插入量
             */
            int nMaxInsertRate4
                    = stuIrisCaps.nMaxInsertRate;
            System.out.println("nMaxInsertRate4:"+nMaxInsertRate4);

            /**
             眼睛信息图片最小尺寸,单位KB
             */
            int nMinIrisPhotoSize
                    = stuIrisCaps.nMinIrisPhotoSize;
            System.out.println("nMinIrisPhotoSize:"+nMinIrisPhotoSize);

            /**
             眼睛信息图片最大尺寸，单位KB
             */
            int nMaxIrisPhotoSize
                    = stuIrisCaps.nMaxIrisPhotoSize;
            System.out.println("nMaxIrisPhotoSize:"+nMaxIrisPhotoSize);

            /**
             每个用户最多支持多少组
             */
            int nMaxIrisGroup
                    = stuIrisCaps.nMaxIrisGroup;
            System.out.println("nMaxIrisGroup:"+nMaxIrisGroup);

            /**
             眼睛识别算法提供标识，0未知，1华
             */
            int nRecognitionAlgorithmVender
                    = stuIrisCaps.nRecognitionAlgorithmVender;
            System.out.println("nRecognitionAlgorithmVender:"+nRecognitionAlgorithmVender);

            /**
             算法(模型)版本号,如果版本号有多位，按Major/Minor从高到低每8bit表示一个版本 如1.5.2表示成0x00010502
             */
            int nRecognitionVersion
                    = stuIrisCaps.nRecognitionVersion;
            System.out.println("nRecognitionVersion:"+nRecognitionVersion);

            /**
             眼睛信息存储上限
             */
            int nMaxIrisesCount
                    = stuIrisCaps.nMaxIrisesCount;
            System.out.println("nMaxIrisesCount:"+nMaxIrisesCount);


        } else {
            System.err.println("GetDevCaps Failed!" + ToolKits.getErrorCode());
        }
    }

    public void RunTest()
    {
        System.out.println("Run Test");
        CaseMenu menu = new CaseMenu();;
        menu.addItem((new CaseMenu.Item(this , "获取门禁能力" , "accesscontrolCaps")));
        menu.run();
    }
    // 配置登陆地址，端口，用户名，密码
    private String m_strIpAddr = "172.13.76.79";
    private int m_nPort = 37777;
    private String m_strUser = "admin";
    private String m_strPassword = "admin321";
    public static void main(String[] args) {
        AccesscontrolCapsDemo demo=new AccesscontrolCapsDemo();
        demo.InitTest();
        demo.RunTest();
        demo.EndTest();

    }

    /**
     * 初始化测试
     */
    public void InitTest() {
        AccesscontrolCapsDemo.Init();
        this.loginWithHighLevel();
    }

    /**
     * 结束测试
     */
    public void EndTest() {
        System.out.println("End Test");
        this.logOut(); // 登出设备
        System.out.println("See You...");
        AccesscontrolCapsDemo.cleanAndExit(); // 清理资源并退出
    }
}
